import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/lib/auth';
import { db } from '@/lib/db';
import { errorHandler } from '@/lib/error-handler';

/**
 * 协作会话API
 * 用于记录用户的协作会话状态，包括在线状态、光标位置等
 */
export async function POST(
  request: NextRequest, 
  { params }: { params: { id: string } }
) {
  try {
    const session = await auth();
    
    if (!session?.user) {
      return new NextResponse(JSON.stringify({ error: '未授权访问' }), { 
        status: 401, 
        headers: { 'Content-Type': 'application/json' } 
      });
    }
    
    const projectId = params.id;
    
    // 检查项目成员权限
    const projectMember = await db.projectMember.findFirst({
      where: {
        projectId,
        userId: session.user.id,
      }
    });
    
    if (!projectMember) {
      return new NextResponse(JSON.stringify({ error: '无权访问此项目' }), { 
        status: 403, 
        headers: { 'Content-Type': 'application/json' } 
      });
    }
    
    const body = await request.json();
    const { documentId, status, cursorPosition, lastActive } = body;
    
    // 更新或创建协作会话
    const collaborationSession = await db.collaborationSession.upsert({
      where: {
        userId_documentId: {
          userId: session.user.id,
          documentId: documentId || '' // 如果没有documentId，使用空字符串作为占位符
        }
      },
      update: {
        status: status || 'active',
        cursorPosition: cursorPosition || null,
        lastActive: lastActive ? new Date(lastActive) : new Date()
      },
      create: {
        userId: session.user.id,
        documentId: documentId || '', // 如果没有documentId，使用空字符串作为占位符
        status: status || 'active',
        cursorPosition: cursorPosition || null,
        lastActive: lastActive ? new Date(lastActive) : new Date()
      }
    });
    
    // 返回更新结果
    return NextResponse.json({
      success: true,
      id: collaborationSession.id,
      status: collaborationSession.status,
      lastActive: collaborationSession.lastActive
    });
    
  } catch (error) {
    console.error('更新协作会话失败:', error);
    return errorHandler(error);
  }
}

/**
 * 获取项目的协作会话列表
 */
export async function GET(
  request: NextRequest, 
  { params }: { params: { id: string } }
) {
  try {
    const session = await auth();
    
    if (!session?.user) {
      return new NextResponse(JSON.stringify({ error: '未授权访问' }), { 
        status: 401, 
        headers: { 'Content-Type': 'application/json' } 
      });
    }
    
    const projectId = params.id;
    
    // 检查项目成员权限
    const projectMember = await db.projectMember.findFirst({
      where: {
        projectId,
        userId: session.user.id,
      }
    });
    
    if (!projectMember) {
      return new NextResponse(JSON.stringify({ error: '无权访问此项目' }), { 
        status: 403, 
        headers: { 'Content-Type': 'application/json' } 
      });
    }
    
    // 获取项目中的所有文档
    const documents = await db.document.findMany({
      where: {
        projectId
      },
      select: {
        id: true
      }
    });
    
    // 获取所有文档的协作会话
    const documentIds = documents.map(doc => doc.id);
    
    const collaborationSessions = await db.collaborationSession.findMany({
      where: {
        documentId: {
          in: documentIds
        },
        // 只获取最近30分钟活跃的会话
        lastActive: {
          gte: new Date(Date.now() - 30 * 60 * 1000)
        }
      },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            image: true
          }
        }
      }
    });
    
    // 返回协作会话列表
    return NextResponse.json(collaborationSessions);
    
  } catch (error) {
    console.error('获取协作会话列表失败:', error);
    return errorHandler(error);
  }
}